<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AccessSystem\IndexController;
use App\Http\Controllers\Controller;
use App\Models\StudyRoomReservationWhite;
use App\Validate\StudyRoomReservationWhiteValidate;
use Illuminate\Support\Facades\DB;

/**
 * 预约白名单类
 */
class StudyRoomReservationWhiteController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new StudyRoomReservationWhite();
        $this->validate = new StudyRoomReservationWhiteValidate();
    }


    /** 
     * 白名单列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param start_time date 搜索开始时间
     * @param end_time date 搜索结束时间
     */
    public function lists()
    {
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $res = $this->model->lists(null, $keywords, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }


    /** 
     * 新增
     * @param username 用户名
     * @param account 账号
     * @param start_time 开始时间  可选
     * @param end_time 结束时间  必选
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $count = $this->model->where('is_del', 1)->count();
        if ($count >= 10) {
            return $this->returnApi(202, "白名单配置不能超过10条，请删除后在进行配置");
        }
        $is_exists = $this->model->nameIsExists($this->request->account, 'account');
        if ($is_exists) {
            return $this->returnApi(202, "该账号已存在");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['start_time'] = $data['start_time'] ? $data['start_time'] : date('Y-m-d H:i:s');
            $this->model->add($data);
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "保存成功", true);
        } catch (\Exception $e) {
            // var_dump($e);exit;
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "保存失败");
        }
    }

    /** 
     * 编辑
     * @param id int 活动id 
     * @param username 用户名
     * @param account 账号
     * @param start_time 开始时间
     * @param end_time 结束时间
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $is_exists = $this->model->nameIsExists($this->request->account, 'account', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该账号已存在");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['start_time'] = $data['start_time'] ? $data['start_time'] : date('Y-m-d H:i:s');
            $this->model->change($data);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "保存成功", "YES");
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "保存失败");
        }
    }

    /** 
     * 删除
     * @param id int 活动id
     */
    public function del()
    {
         //增加验证场景进行验证
         if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }


    /** 
     * 出示二维码
     * @param id int 活动id
     */
    public function getApplyQr()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_white_qr')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $res = $this->model->where('id', $this->request->id)->first();

        if ($res && $res['end_time'] > date('Y-m-d H:i:s')) {
            //可以出示二维码
            $accessSystemObj = new IndexController();
            $minute = floor((strtotime($res['end_time']) - time()) % 86400 / 60);
            $qr_url = $accessSystemObj->createQr($res['account'], 'AIl_Viewld', $minute);
            if ($qr_url) {
                return $this->returnApi(200, "二维码生成成功", true, ['qr_url' => $qr_url]);
            }
            return $this->returnApi(202, '二维码生成失败，请重试！');
        }
        return $this->returnApi(202, "白名单不存在或已过期");
    }
}
